import java.util.Arrays;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-08-01
 * Time: 23:28
 */
public class Solution {
    public int maxOperations(int[] nums, int k) {
        Arrays.sort(nums);
        int l = 0, r = nums.length - 1;
        int ans = 0;
        while (l < r) {
            int res = nums[l] + nums[r];
            if (res > k) {
                r--;
            } else if (res < k) {
                l++;
            } else {
                ans++;
                l++;
                r--;
            }
        }
        return ans;
    }


    public int maxOperations2(int[] nums, int k) {
        int result = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int x : nums) {
            map.put(x, map.getOrDefault(x, 0)+1);
        }
        for (int x : nums) {
            if (map.getOrDefault(x, 0) > 0) {
                // x 还没有使用完
                if (map.getOrDefault(k-x, 0) > 0) {
                    map.put(x, map.getOrDefault(x, 0)-1);
                    map.put(k-x, map.getOrDefault(k-x, 0)-1);
                    // 可能出现 k-x == x 的情况, 这种情况下会多算
                    if (map.get(x) >= 0) {
                        result++;
                    }
                }
            }
        }
        return result;
    }



}
